package com.gyms.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.ViewGroup;

import com.classic.okhttp.beans.HVAreaBean;
import com.gyms.fragment.AreaFragment;

import java.util.ArrayList;
import java.util.List;

import cn.finalteam.toolsfinal.adapter.FragmentAdapter;

/**
 * Created by ltx on 17/12/28
 */

public class CommonFragmentPagerAdapter extends FragmentAdapter {
    private List<Fragment> mFragmentList;
    private List<String> mTagList; // 用来存放所有Fragment的 Tag
    private FragmentManager mFragmentManager;
    public CommonFragmentPagerAdapter(FragmentManager fm, List<Fragment> list) {
        super(fm, list);
        mFragmentList= list;
        mTagList=new ArrayList<>();
        mFragmentManager=fm;
    }

    // 直接从 FragmentPageAdapter 源码里拷贝 Fragment 生成 Tag 的方法
    private String makeFragmentName(int viewId, int index) {
        return "android:switcher:" + viewId + ":" + index;
    }

    @Override
    public Fragment getItem(int position) {
        return null==mFragmentList?null:mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return null==mFragmentList?0:mFragmentList.size();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        mTagList.add(position, makeFragmentName(container.getId(),
                (int) getItemId(position)));
        return super.instantiateItem(container, position);
    }
    public void update(int position, List<HVAreaBean> mAreaBeans) {
        Fragment fragment = mFragmentManager.findFragmentByTag(mTagList.get(position));
        if (fragment == null) return;
        if (fragment instanceof AreaFragment) {
            ((AreaFragment)fragment).updateAreaBeans(mAreaBeans);
        }
        notifyDataSetChanged();
    }
}
